package mi.payment.utils.transaction;

import android.content.Context;
import android.text.TextUtils;

import java.util.HashMap;
import java.util.Map;

import mi.payment.settings.MerManagerSettings;
import mi.payment.settings.SystemParamsSettings;
import mi.payment.constants.TransactionBitmap;

import mi.payment.utils.iso8583.EncodePackage;
import mi.payment.utils.iso8583.MsgField;
import mi.payment.utils.iso8583.Utils;
import mi.payment.utils.secure.TerminalSecure;
import sunmi.sunmiui.utils.LogUtil;

/**
 * POS状态上送(可用于 AID tags 获取、RID tag获取等)
 *
 * @author tomcat on 2017/2/17.
 */
class POSStatusUpload extends TransactionTask<String, Void, String> {

    POSStatusUpload(Context c) {
        super(c, false);
    }

    @Override
    protected void onBegin(String[] params) {
    }

    @Override
    protected String appointResult() {
        return resultStr;
    }

    @Override
    protected Map<String, MsgField> preAssembly() {
        return EncodePackage.preAssemblyBase(TransactionBitmap.BITMAP_AID_SEEK);
    }

    @Override
    protected byte[] changeAndAssembly(Map<String, MsgField> fieldMap) {
        String value60_3 = params[0];
        String value62 = params[1];

        MerManagerSettings merchantParams = merchantSettingsOperation.getMerManagerSettings();
        SystemParamsSettings systemParams = mSystemParamsOperation.getSystemParamsSettings();

        MsgField f041 = fieldMap.get("F041");
        f041.setDataStr(merchantParams.getTerminalNum());

        MsgField f042 = fieldMap.get("F042");
        f042.setDataStr(merchantParams.getMerchantNum());

        MsgField f060 = fieldMap.get("F060");
        f060.setDataStr("00" + systemParams.getBatchNumStart() + value60_3);
        f060.setDataLength(11);

        if (TextUtils.isEmpty(value62)) {
            fieldMap.remove("F062");
        } else {
            MsgField f062 = fieldMap.get("F062");
            f062.setDataStr(value62);
            f062.setDataLength(value62.length());
        }

        return EncodePackage.assembly(fieldMap, "0820", TerminalSecure.PROCESSREQUEST_NONE);
    }

    @Override
    protected void onUnpacked(HashMap<String, MsgField> resp) {
        if (TextUtils.equals("00", resultStr)) {
            MsgField f062_r = resp.get("F062");
            if (f062_r != null) {
                resultStr = Utils.byte2HexStr(f062_r.getDataBytes());
                LogUtil.e("nsz", "pos状态上送结果：" + resultStr);
            }
        }
    }

}
